package com.studentManagement.servlet;

import com.studentManagement.daoImpl.StudentDaoImpl;
import com.studentManagement.daoImpl.TeacherDaoImpl;
import com.studentManagement.po.Student;
import com.studentManagement.po.Teacher;
import com.studentManagement.serviceImpl.TeacherServiceImpl;
import com.studentManagement.utils.CookieUtil;
import com.studentManagement.utils.Md5Util;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.GeneralSecurityException;
import java.sql.SQLException;
import java.util.Properties;
import java.util.UUID;


/**
 * Created by Administrator on 2017/4/25 0025.
 */
public class LoginServlet extends javax.servlet.http.HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String action = request.getParameter("action");
        if (action.equals("login")) {
            doLogin(request, response);//登录
        } else if (action.equals("logout")) {
            doLogout(request, response);//注销
        } else if (action.equals("verifyId")) {
            verifyId(request, response);//验证账户名是否已被注册
        } else if (action.equals("register")) {
            doRegister(request, response);//注册
        } else if (action.equals("doActivate")) {
            doActivate(request, response);//激活
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }

    /**
     * 方法的功能描述：登录验证
     *
     * @params：[request, response]
     * @return: void
     */
    private void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String identity = request.getParameter("identity");
        String username = request.getParameter("username");
        //md5加密的密码
        String password = Md5Util.md5(request.getParameter("password"));
        //真假验证码
        String inputValidateCode = request.getParameter("validateCode");
        String trueValidateCode = (String) request.getSession().getAttribute("code");
        //根据登录者身份，选择不同的验证
        //验证 验证码（不区分大小写）
//        if ((inputValidateCode.toLowerCase()).equals(trueValidateCode.toLowerCase())){
        if (true) {
            if (identity.equals("teacher")) {
                //教师登录
                Teacher teacher = null;
                try {
                    teacher = new TeacherDaoImpl().queryTeacherByTId(username);
                    if (teacher.getTeacher_state() == 1) {
                        if (password.equals(teacher.getTeacher_key())) {
                            request.getSession().setAttribute("teacher", teacher);
                            //是否保存cookie到客户端
                            if ("on".equals(request.getParameter("checkbox"))) {
                                CookieUtil.saveUsernameAndpassword_day(response, username, password, 14);
                            }
                            response.sendRedirect(request.getContextPath() + "/jsp/teacher/index.jsp");
                        } else {
                            request.getSession().setAttribute("err", "密码错误！");
                            response.sendRedirect(request.getContextPath() + "/jsp/teacher/login.jsp");
                        }
                    } else {
                        request.getSession().setAttribute("err", "邮箱未激活！");
                        response.sendRedirect(request.getContextPath() + "/jsp/teacher/login.jsp");
                    }

                } catch (Exception e) {
                    request.getSession().setAttribute("err", "用户名错误！");
                    response.sendRedirect(request.getContextPath() + "/jsp/teacher/login.jsp");
                }

            }

            //学生登录
            else if (identity.equals("student")) {
                Student student;
                try {
                    student = new StudentDaoImpl().queryStudentDetail(username);
                    if (password.equals(student.getStudent_key())) {
                        request.getSession().setAttribute("student", student);
                        //是否保存cookie到客户端
                        if ("on".equals(request.getParameter("checkbox"))) {
                            CookieUtil.saveUsernameAndpassword_day(response, username, password, 14);
                        }
                        response.sendRedirect(request.getContextPath() + "/jsp/student/index.jsp");
                    } else {
                        request.getSession().setAttribute("err", "密码错误！");
                        response.sendRedirect(request.getContextPath() + "/jsp/student/login.jsp");
                    }
                } catch (Exception e) {
                    request.getSession().setAttribute("err", "用户名错误！");
                    response.sendRedirect(request.getContextPath() + "/jsp/student/login.jsp");
                }
            }
        } else {
            request.getSession().setAttribute("err", "验证码错误！");
            response.sendRedirect(request.getContextPath() + "/jsp/" + identity + "/login.jsp");
        }
    }

    /**
     * 方法的功能描述：注销登录
     *
     * @params：[request, response]
     * @return: void
     */
    private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String identity = request.getParameter("identity");
        Cookie cookie = new Cookie("autoUsername", null);
        Cookie cookie2 = new Cookie("autoPassword", null);
        cookie.setMaxAge(0);
        cookie2.setMaxAge(0);
        response.addCookie(cookie);
        response.addCookie(cookie2);
        request.getSession().removeAttribute(identity);
        request.getRequestDispatcher(request.getContextPath() + "/jsp/" + identity + "/login.jsp").forward(request,response);
    }

    /**
     * 方法的功能描述：验证教师id/学生id是否可用
     *
     * @params：[request, response]
     * @return: void
     */
    private void verifyId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String identity = request.getParameter("identity");
        PrintWriter out = response.getWriter();
        if (identity.equals("teacher")) {
            String teacher_id = request.getParameter("teacher_id");
            boolean boo = new TeacherServiceImpl().verifyTeacher_id(teacher_id);
            out.print(boo);
        } else if (identity.equals("student")) {

        }
    }

    /**
     * 方法的功能描述：注册
     *
     * @params：[request, response]
     * @return: void
     */
    private void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String identity = request.getParameter("identity");
        //教师注册
        if (identity.equals("teacher")) {
            //获取前端数据
            String teacher_id = request.getParameter("teacher_id");
            String teacher_key = request.getParameter("teacher_key");
            String teacher_email = request.getParameter("teacher_email");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //注册用户的准备数据
            Teacher teacher = new Teacher();
            teacher.setTeacher_id(teacher_id);
            teacher.setTeacher_key(Md5Util.md5(teacher_key));
            teacher.setTeacher_email(teacher_email);
            teacher.setTeacher_state(0);//0表示未激活吗，1表示已激活
            teacher.setTeacher_uuid(uuid);//生成uuid激活码
            //注册
            try {
                boolean boo = new TeacherDaoImpl().addTeacher(teacher);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //发送邮件
            try {
                sentMail(request, response, teacher_email, uuid, identity);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            response.sendRedirect(request.getContextPath() + "/jsp/activate.jsp");

        }//学生注册
        else if (identity.equals("student")) {

        }


    }

    /**
     * 方法的功能描述：发送邮件
     *如出现报错，请及时更新qq账号，及授权码，qq改密会导致授权码过期
     * @params：[request, response, addressee 收件人邮箱, uuid]
     * @return: void
     */
    private void sentMail(HttpServletRequest request, HttpServletResponse response, String addressee, String uuid, String toIdentity) throws IOException, MessagingException, GeneralSecurityException {
        // 收件人电子邮箱
        String to = addressee;
        // 发件人电子邮箱
        String from = "595726017@qq.com";
        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.qq.com";  //QQ 邮件服务器
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("595726017@qq.com", "jbnubspogdyebffi"); //发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // Set Subject: 头部头字段
            message.setSubject("来自南信院学生管理系统的激活邮件");
            // 设置消息体
            message.setContent("<h1>来自南信院学生管理系统的激活邮件,不是本人操作请忽视此邮件，激活请点击以下链接：</h1><h3><a href='http://localhost:8080/login?action=doActivate&identity=" + toIdentity + "&uuid=" + uuid + "'>点我跳转</a></h3>", "text/html;charset=utf-8");
            // 发送消息
            Transport.send(message);
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

    /**
     * 方法的功能描述：处理激活邮件
     *
     * @params：[request, response]
     * @return: void
     */
    private void doActivate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uuid = request.getParameter("uuid");
        String identity = request.getParameter("identity");
        //激活教师邮箱
        if (identity.equals("teacher")) {
            boolean boo = false;//true表示状态：1, uuid：null  修改成功
            Teacher teacher = null;
            try {
                teacher = new TeacherDaoImpl().queryTeacher(uuid);
                if (teacher != null) {
                    teacher.setTeacher_state(1);
                    teacher.setTeacher_uuid("");
                    boo = new TeacherDaoImpl().updateTeacher(teacher, teacher.getTeacher_id());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (boo) {
                //identity：老师/学生   &state：成功/0失败
                response.sendRedirect(request.getContextPath() + "/jsp/activateTip.jsp?identity=teacher&state=1");
            } else {
                response.sendRedirect(request.getContextPath() + "/jsp/activateTip.jsp?identity=teacher&state=0");
            }

        }
        //激活学生邮箱
        else if (identity.equals("student")) {

        }

    }
}

